<template>
  <div class="app">
    <!-- <el-tabs class="tabContent" v-model="activeName" @tab-click="handleClick"> -->
    <!-- <el-tab-pane :label="$t('home.accountLogin')" name="first"> -->
    <!-- ref="ruleForm" :rules="rules" :model="ruleForm"  class="demo-ruleForm" -->
    <el-form label-width="0">
      <!-- 按钮 -->
      <!-- <el-form-item>
            <el-button @click="Login_k" style="width: 100%" type="primary">{{
              $t("home.logIn")
            }}</el-button>
          </el-form-item> -->

      <div class="zhonxin">
        <!-- 验证码 -->
        <div
          style="
            width: 33px;
            height: 22px;
            cursor: pointer;
            line-height: 22px;
            position: absolute;
            top: 408px;
            right: 64px;
            z-index: 1;
            color: #f55651;
          "
        >
          <span v-show="show" @click="getCode">GET</span>
          <span
            style="
              width: 50px;
              margin-left: -85px;
              color: #999999;
              pointer-events: none;
            "
            v-show="!show"
            class="count"
            >Reacquire {{ count }} s</span
          >
        </div>
        <!-- input框 -->
        <div class="form-tiele">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="0px"
            class="demo-ruleForm"
          >
            <div style="color: #333333; font-size: 16px; font-weight: bold">
              Email
            </div>
            <el-form-item style="margin-top: 10px" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <div style="color: #333333; font-size: 16px; font-weight: bold">
              Verify Code
            </div>
            <el-form-item style="margin-top: 10px" prop="code">
              <el-input
                style="position: relative"
                v-model="ruleForm.code"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                style="
                  width: 377px;
                  color: #fff;
                  background: linear-gradient(to right, #ee685a, #e25177);
                  margin-top: 20px;
                "
                @click="submitForm('ruleForm', 6)"
                >Sign in</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="OR">
          <div class="left"></div>
          <div class="in">OR</div>
          <div class="right"></div>
        </div>
        <div class="Thirdparty">
          <div class="GooleD" @click="FacebookOn(8)">
            <img src="../../../assets/GooleD.png" alt="" />
            <fb-signin-button
              style="
                position: absolute;
                top: 0px;
                left: 42px;
                width: 40px;
                height: 40px;
              "
              id="signout"
              :params="fbSignInParams"
              @success="onSignInSuccessFB"
              @error="onSignInErrorFB"
            >
            </fb-signin-button>
          </div>
          <div class="FbacebookD" @click="GoogleOn(7)">
            <img src="../../../assets/FacebookD.png" alt="" />
            <g-signin-button
              style="
                position: absolute;
                top: 0px;
                left: 166px;
                width: 40px;
                height: 40px;
              "
              :params="googleSignInParams"
              @success="onSignInSuccess"
              @error="onSignInError"
            >
            </g-signin-button>
          </div>
          <div class="AppleD">
            <!-- <img src="../../../assets/AppleD.png" alt="" /> -->
            <vue-apple-signin
              color="black"
              data-border="false"
              data-border-radius="50"
              data-mode="logo-only"
            >
            </vue-apple-signin>
          </div>
        </div>
      </div>
      <!-- 登录失败提示弹框--开始 -->
      <div class="ON_login" v-if="ON_login_false">
        <div class="neirong">
          <div class="shang">Login failed, please try again.</div>
          <div class="xia" @click="ON_login">OK</div>
        </div>
      </div>
      <!-- 登录失败提示弹框--结束 -->
    </el-form>
    <!-- </el-tab-pane> -->
    <!-- </el-tabs> -->
  </div>
</template>

<script  type="text/javascript">
// import { signIn, signCode, testDele, demo } from "@/api/info";
import { phoneRex } from "@/utils/checkValue";
import { VerificationCode, Lonsignin, getCode } from "@/api/info";
export default {
  name: "facebook",
  data() {
    var ruleNumber = (rule, value, callback) => {
      var myreg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
      if (value === "") {
        callback(new Error("Please enter email."));
      } else if (!myreg.test(value)) {
        callback(new Error("That is not a valid email address."));
      } else {
        callback();
      }
    };
    return {
      activeName: "first",
      Applecode: "",
      params: "",
      NOuserName: "",
      NOheadimgurl: "",
      ListuserInfo: [],
      ListuserInfoss: [],
      login: true,
      username: this.$t("home.assignedUserName"),
      msgNum: null,
      // hide: true, //新增首页--Log in -- 隐藏
      // moren: false, //已登陆
      signout: false, //退出登录
      popup_is: false,
      Login_On: false,
      ON_login_false: false,
      googleSignInParams: {
        client_id:
          "139301213659-qqqlitnpvv0sagl7m96agrfbd9lujqs0.apps.googleusercontent.com",
      },
      fbSignInParams: {
        scope: "email,user_likes",
        return_scopes: true,
      },
      googleId: "",
      googleImg: "",
      googleusername: "",
      facebookuserid: "",
      facebookUsername: "",
      regEmail: "",
      is_type: "",
      show: true,
      count: "",
      timer: null,
      nihaoma: "",
      ruleForm: {
        phone: "",
        code: "",
      },

      rules: {
        phone: [{ validator: ruleNumber, trigger: "blur" }],
        code: [
          {
            required: true,
            message: "Please enter the verification code.",
            trigger: "blur",
          },
          {
            min: 4,
            max: 4,
            message: "This is not a valid verification code.",
            trigger: "blur",
          },
        ],
      },
    };
  },
  inject: ["reload"],
  methods: {
    Login_k() {
      this.Login_On = true;
    },
    handleClick(tab, event) {},
    onSignInSuccess(googleUser) {
      // console.log(googleUser);
      const profile = googleUser.getBasicProfile();
      this.googleusername = profile.sf; //姓名
      this.googleImg = profile.MN; //头像
      this.googleId = profile.eX; //唯一id
      // console.log(profile);
      //调用登录接口
      this.onsubmit();
    },
    onSignInError(error) {
      // console.log(error, "登录失败回调Goole");
    },

    //Google传参
    GoogleOn(e) {
      this.is_type = e;
    },
    //Facebook传参
    FacebookOn(e) {
      this.is_type = e;
    },
    // 谷歌第三方登录--结束
    // Facebook第三方登录--开始
    onSignInSuccessFB(response) {
      // 登录成功回调
      FB.api("/me", (dude) => {
        this.facebookUsername = `${dude.name}`;
      });
      this.facebookuserid = response.authResponse.userID;
      //调用登录接口
      this.onsubmit();
      // console.log(response, "返回第三方的登录信息"); //返回第三方的登录信息 tolen等
    },
    onSignInErrorFB(error) {
      // console.log(error, "登录失败回调Facebook");
      //登录失败回调
    },
    // Facebook第三方登录--结束
    ONsignout() {
      this.signout = true;
      this.popup_is = true;
    },
    setpopup_is() {
      this.signout = false;
      this.popup_is = false;
    },
    // 用户退出
    logout() {
      this.$store.commit("setUserInfo", "");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
      this.clearAllCookie();
      this.$router.push("/");
      // this.reload();
    },
    clearAllCookie() {
      var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
      if (keys) {
        for (var i = keys.length; i--; )
          document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
      }
    },
    //用户点击登录
    Clicklogin() {
      this.Login_On = true;
    },
    //验证码倒计时
    getCode() {
      let verifys = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        if (this.ruleForm.phone == "") {
          this.show = true;
          return;
        } else if (!verifys.test(this.ruleForm.phone)) {
          this.show = true;
          return;
        } else {
          this.show = false;
          this.sendPhoneMessage();
        }
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    //发送验证码接口
    sendPhoneMessage() {
      VerificationCode(this.ruleForm.phone).then(
        (res) => {},
        (fail) => {}
      );
    },
    //关闭登录
    close() {
      this.Login_On = false;
    },
    // 登录失败
    ON_login() {
      this.ON_login_false = false;
    },
    //登录接口
    onsubmit() {
      if (this.is_type == 6) {
        this.params = {
          code: this.ruleForm.code,
          openid: this.ruleForm.phone,
          type: this.is_type,
        };
      } else if (this.is_type == 7) {
        this.params = {
          openid: this.googleId,
          headImgUrl: this.googleImg,
          nickname: this.googleusername,
          type: this.is_type,
        };
      } else if (this.is_type == 8) {
        this.params = {
          openid: this.facebookuserid,
          type: this.is_type,
        };
      }
      Lonsignin(this.params).then((res) => {
        if (res.code == 1) {
          this.$store.commit("setUserInfo", res.source);
          localStorage.setItem("userInfo", JSON.stringify(res.source));
          sessionStorage.setItem("userInfo", JSON.stringify(res.source));
          //存token
          localStorage.setItem("token", res.source.token);
          this.reload();
        }
      });
    },
    // 点击登录
    submitForm(formName, e) {
      this.is_type = e;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.onsubmit();
        } else {
          return false;
        }
      });
    },
    // 查询apple返回用户信息
    getCodes() {
      getCode(this.Applecode).then(
        (res) => {
          if (res.code == 1) {
            // let userInfos = res.source;
            this.$store.commit("setUserInfo", res.source);
            localStorage.setItem("userInfo", JSON.stringify(res.source));
          }
        },
        (fail) => {
          console.log(fail);
        }
      );
    },
    // setWxerwma() {
    //   const obj = new WxLogin({
    //     self_redirect: true,
    //     id: "login_container", // 需要显示的容器id
    //     appid: "wxef5765dd395d8504", // 公众号appid wx*******
    //     scope: "snsapi_login", // 网页默认即可
    //     redirect_uri: encodeURIComponent(
    //       "https://passport.zcool.com.cn/thirdlogin/wechat_callback.do?appId=1006"
    //     ), // 授权成功后回调的
    //     state: Math.ceil(Math.random() * 1000), // 可设置为简单的随机数加session用来校验
    //     style: "black", // 提供"black"、"white"可选。二维码的样式
    //     href: "https://static.zcool.cn/passport4.0/css/wxCode.css?v=0.1", // 外部css文件url，需要https
    //   });
    // },
    // 60s发送一次前端实现
    // timeOver() {
    //   var that = this;
    //   var timeo = 60;
    //   this.getCode.disabled = true;
    //   var timeStop = setInterval(function () {
    //     timeo--;
    //     if (timeo > 0) {
    //       // that.text('重新发送' + timeo +'s');
    //       // this.$set(getCode,value,'重新发送' + timeo +'s')
    //       that.getCode.value = that.$t("home.resend") + timeo + "s";
    //     } else {
    //       timeo = 60; //当减到0时赋值为60
    //       // that.$set(getCode, value, '获取验证码')
    //       that.getCode.value = that.$t("home.getCode");
    //       clearInterval(timeStop); //清除定时器
    //       that.getCode.disabled = false;
    //     }
    //   }, 1000);
    // },
    // 发送手机验证码-开始
    // sendCode() {
    //   this.$refs["form"].validate((valid) => {
    //     if (valid) {
    //       this.sendPhoneMessage();
    //       this.timeOver();
    //     } else {
    //       return false;
    //     }
    //   });
    // },
    //发送手机验证码-结束

    // sendPhoneMessage() {
    //   signCode({codeType: 2, phone: this.form.phone}).then((res)=>{
    //     // console.log(res,888)
    //     // console.log(this.form.phone,'取手机号')
    //   },fail=>{
    //     console.log(fail)
    //   })
    // },

    // 用户登录
    // onSubmit() {
    //   let params = { code: this.form.code, telephone: this.form.phone };

    //   if (this.form.authorize) {
    //     //判断是否同意隐私政策
    //     signIn(params).then((res) => {
    //       console.log(res)
    //       if (res.code == 200016 || res.code == 200017) {
    //         //判断是否注册成为作者
    //         this.$router.push({ path: "/improveInfor" });
    //       }
    //       if (res.code == 1) {
    //         let userInfo = res.source;
    //         this.$store.state.userInfo = userInfo;
    //         sessionStorage.setItem("userInfo", JSON.stringify(res.source));
    //         localStorage.setItem("userInfo", JSON.stringify(res.source));
    //         if (this.form.savePhone) {
    //           localStorage.setItem("autherPhone", this.form.phone);
    //         }
    //       }
    //     });
    //   } else {
    //     this.$message({
    //       type: "error",
    //       message: this.$t("home.agreePrivacyAndAgreement"),
    //     });
    //   }
    // },
    //测试删除用户
    // deletPhone() {
    //   testDele({ isDeleteUser: 1, phone: 18210141211 }).then((res) => {});
    // },
    // localStorageFn() {
    //   //判断是否有本地账号信息
    //   if (localStorage.getItem("autherPhone")) {
    //     this.form.phone = localStorage.getItem("autherPhone");
    //   }
    // },
  },
  created() {
    this.Applecode = this.$route.query.code;
    if (this.Applecode != undefined) {
      this.getCodes();
    }
  },
  mounted() {
    // this.localStorageFn();
    // this.setWxerwma();
    // this.deletPhone()
    // history.pushState(null, null, document.URL);
    // window.addEventListener("popstate", function () {
    //   history.pushState(null, null, document.URL);
    // });
  },
  computed: {
    bTrue: function () {
      return this.$store.getters.userInfo.token;
    },
    userInfo() {
      return this.$store.getters.userInfo;
    },
  },
};
</script>
<style lang="scss">
.tabContent .form_box .el-form-item__content {
  display: flex;
  justify-content: flex-end;
}
.tabContent
  .el-form-item
  .el-form-item__content
  .el-checkbox
  .el-checkbox__label {
  color: #999;
}
.ON_login {
  width: 510px;
  height: 240px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: #ffffff;
  border-radius: 16px;
  display: flex;
  justify-content: center;
  .neirong {
    width: 398px;
    height: 137px;
    margin-top: 71px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    .shang {
      width: 340px;
      height: 33px;
      text-align: center;
      line-height: 33px;
      font-size: 24px;
      color: #333333;
    }
    .xia {
      width: 100%;
      height: 48px;
      border-radius: 8px;
      background: linear-gradient(to right, #ee685a, #e25177);
      font-size: 24px;
      color: #ffffff;
      text-align: center;
      line-height: 48px;
      cursor: pointer;
    }
  }
}
.OR {
  width: 100%;
  height: 24px;
  margin-top: 23px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    width: 171px;
    height: 1px;
    background: #eeeeee;
  }
  .in {
    color: #666666;
  }
  .right {
    width: 171px;
    height: 1px;
    background: #eeeeee;
  }
}
.Thirdparty {
  width: 100%;
  height: 40px;
  margin-top: 16px;
  position: relative;
  display: flex;
  justify-content: space-around;
  .GooleD {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
  .FbacebookD {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
  .AppleD {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
}
</style>
<style lang="scss" scoped="scoped">
::v-deep .el-tabs__item {
  font-size: 16px;
}
::v-deep .is-active {
  color: #3385fd !important;
}

::v-deep .el-input__inner {
  border-radius: 8px;
  line-height: 44px;
  height: 44px;
}
::v-deep .el-button {
  border-radius: 8px;
  height: 44px;
}
::v-deep .el-tabs__active-bar {
  background-color: #3385fd;
}
.el-button--primary {
  background-color: #3385fd;
  border: #3385fd;
}

::v-deep .el-tabs__nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
::v-deep .el-tabs__active-bar {
  background-color: #e4e7ed;
}
::v-deep .is-active {
  border-bottom: 2px solid #3385fd;
  position: relative;
  z-index: 100;
}
.qqContent {
  display: flex;
  flex-direction: column;
  align-items: center;
  .infoMess {
    margin: 10px 0;
  }
}
.agreement {
  a {
    font-size: 16px;
    color: #3385fd;
  }
  span {
    font-size: 16px;
    margin-left: 10px;
  }
}
.el-form-item {
  //   margin-bottom: 6px;

  >>> &__content {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 22px;
  }
}
.authorize_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
#login_container {
  height: 300px;
}
</style>